package com.mriassl.stream.receiver;

import java.text.MessageFormat;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import com.mriassl.stream.constant.TransactionType;
import com.mriassl.stream.lib.rabbitmq.RabbitMQConst;
import com.mriassl.stream.service.LotteryService;


@Component
@RabbitListener(queues=RabbitMQConst.QUEUE_FOR_BETTING_REPLY_FAIL_NSF)
public class BettingFailNSFReplyReceiver {
    private final Logger log = LoggerFactory.getLogger(BettingFailNSFReplyReceiver.class);
    private Pattern pattern = Pattern.compile("^state:0,busno:(\\w+)$");

    @Autowired
    private LotteryService lotteryService;
    
    @RabbitHandler
    public void receiveReply(String reply) {
        if (StringUtils.isBlank(reply)) return;
        Matcher matcher = pattern.matcher(reply);
        if (matcher.find()) {
            String busno = matcher.group(1);
            String betno = busno.substring(TransactionType.BETTING.getIndex());
            log.error(MessageFormat.format("投注账单金额大于账户可用金额，投注单编号：{0}", betno));
            lotteryService.updateBettingInvalidByBetno(betno);
            // 发送投注扣款失败通知：账户余额不足
            
        }
    }

}
